﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("SysRoleMaster")]
	public class SysRoleMasterController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			return View();
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, SysRoleMasterModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = DbContext.SysRoleMaster.AsNoTracking().Where(x => !string.IsNullOrEmpty(x.Status));

			if (!string.IsNullOrWhiteSpace(model.SelRoleName))
			{
				sql = sql.Where(x => x.RoleName.Contains(model.SelRoleName));
			}

			int total = await sql.CountAsync();

			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.Sort).ThenByDescending(x => x.UpdateDate).ThenBy(x => x.RoleName).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();

			var result = sqlResult.Select(x => new
			{
				ID = x.ID,
				RoleName = x.RoleName,
				Status = x.Status,
				Sort = x.Sort,
				Remark = x.Remark,
				Creator = x.Creator,
				CreateIP = x.CreateIP,
				CreateDate = LoginUser.Language == ConstValues.Language.Cn ?
							x.CreateDate.Value.ToString("yyyy-MM-dd") :
							x.CreateDate.Value.ToString("MM/dd/yyyy")
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetEditData(string id)
		{
			var result = await DbContext.SysRoleMaster.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);

			if (result != null)
			{
				return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> Create(SysRoleMasterModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var result = await DbContext.SysRoleMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID != model.Id &&
						x.RoleName == model.RoleName);
			if (result != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
						string.Format(Resources.MsgRecordExist, Resources.RoleName)),
						JsonRequestBehavior.AllowGet);
			}

			var sysRoleMaster = new SysRoleMaster
			{
				ID = Utility.GetTableId(ConstValues.TableName.SysRoleMaster),
				RoleName = model.RoleName?.Trim(),
				Status = model.Status,
				Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort,
				Remark = model.Remark?.Trim(),
				Creator = LoginUser.UserName,
				CreateIP = LoginUser.IP,
				CreateDate = DateTime.Now
			};

			DbContext.SysRoleMaster.Add(sysRoleMaster);
			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> Modify(SysRoleMasterModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var exist = await DbContext.SysRoleMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID != model.Id && x.RoleName == model.RoleName);
			if (exist != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
						string.Format(Resources.MsgRecordExist, Resources.RoleName)),
						JsonRequestBehavior.AllowGet);
			}

			var result = await DbContext.SysRoleMaster
					.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result != null)
			{
				if (result.RoleName == ConstValues.SA && model.RoleName != ConstValues.SA)
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(Resources.CfmCanNotEditAdmin),
							JsonRequestBehavior.AllowGet);
				}

				result.RoleName = model.RoleName?.Trim();
				result.Status = model.Status;
				result.Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort;
				result.Remark = model.Remark?.Trim();
				result.Updater = LoginUser.UserName;
				result.UpdateIP = LoginUser.IP;
				result.UpdateDate = DateTime.Now;

				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> Delete(SysRoleMasterModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var result = await DbContext.SysRoleMaster
					.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result != null)
			{
				if (result.RoleName == ConstValues.SA)
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(Resources.CfmCanNotDeleteAdmin),
							JsonRequestBehavior.AllowGet);
				}

				using (var transaction = DbContext.Database.BeginTransaction())
				{
					DbContext.SysRoleMaster.Remove(result);

					var sysUserAndRoleRelationList = await DbContext.SysUserAndRoleRelation
							.Where(x => x.RoleId == model.Id).ToListAsync();
					DbContext.SysUserAndRoleRelation.RemoveRange(sysUserAndRoleRelationList);

					var sysGroupAndRoleRelationList = await DbContext.SysGroupAndRoleRelation
							.Where(x => x.RoleId == model.Id).ToListAsync();
					DbContext.SysGroupAndRoleRelation.RemoveRange(sysGroupAndRoleRelationList);

					var sysRoleAndActionRelationList = await DbContext.SysRoleAndActionRelation
							.Where(x => x.RoleId == model.Id).ToListAsync();
					DbContext.SysRoleAndActionRelation.RemoveRange(sysRoleAndActionRelationList);

					await DbContext.SaveChangesAsync();
					transaction.Commit();
				}

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessDelete),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		public async Task<JsonCamelCaseResult> GetActionData(string roleId, SysRoleMasterModel model)
		{
			var sql = DbContext.SysRoleAndActionRelation.AsNoTracking()
					.Where(x => x.Status == ConstValues.Status.正常 &&
						x.RoleId == roleId);

			var sqlResult = await sql.ToListAsync();
			var result = sqlResult.Select(x => new
			{
				ID = x.ID,
				RoleName = DbContext.SysRoleMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.RoleId)?.RoleName,
				ActionName = DbContext.SysActionMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.ActionId)?.ActionName,
			})
			.OrderBy(x => x.ActionName).ToList();

			return JsonCamelCase(new
			{
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonResult> GetAction(SysRoleMasterModel model)
		{
			var result = await DbContext.SysActionMaster.AsNoTracking()
				.Where(x => x.Status == ConstValues.Status.正常)
				.OrderBy(x => x.Sort)
				.ThenBy(x => x.ActionName)
				.Select(x => new
				{
					Id = x.ID,
					ActionName = x.ActionName
				})
				.ToListAsync();

			return JsonCamelCase(result, JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonResult> CreateAction(SysRoleMasterModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			for (int index = 0; index < model.ActionId.Length; index++)
			{
				var temp = model.ActionId[index];
				var result = await DbContext.SysRoleAndActionRelation
					.FirstOrDefaultAsync(x => x.RoleId == model.RoleId &&
					    x.ActionId == temp);
				if (result == null)
				{
					var SysRoleAndActionRelation = new SysRoleAndActionRelation
					{
						ID = Utility.GetTableId(ConstValues.TableName.SysRoleAndActionRelation),
						RoleId = model.RoleId,
						ActionId = temp,
						Status = ConstValues.Status.正常,
						Sort = ConstValues.DefaultSort,
						Remark = string.Empty,
						Creator = LoginUser.UserName,
						CreateIP = LoginUser.IP,
						CreateDate = DateTime.Now
					};

					DbContext.SysRoleAndActionRelation.Add(SysRoleAndActionRelation);
				}
			}
			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
				JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> DeleteAction(SysRoleMasterModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var result = await DbContext.SysRoleAndActionRelation.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result != null)
			{
				DbContext.SysRoleAndActionRelation.Remove(result);
				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessDelete),
					JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
					JsonRequestBehavior.AllowGet);
			}
		}
	}
}